﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Text;
using Traceability.App.Infrastructure.Implement;
using Traceability.App.Infrastructure.Interface;

namespace Traceability.App.API.Extensions
{
    public static class ServiceCollectionExtensions
    {

        public static IServiceCollection AddService(this IServiceCollection services)
        {
            services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            services.AddAutoMapper(typeof(MyAutoMapper));
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            return services;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="MyDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqllog">是否打印执行EF语句转义的sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<MyDbContext>(this IServiceCollection services, string? connectionString, bool enableSqllog) where MyDbContext : DbContext
        {
            return services.AddDbContext<MyDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString
                //    , action =>
                //{
                //    action.EnableRetryOnFailure(
                //          maxRetryCount: 10,
                //          maxRetryDelay: TimeSpan.FromSeconds(60),
                //          errorNumbersToAdd: null);
                //}
                ).EnableSensitiveDataLogging();
                if (enableSqllog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
                    }));
                }
            });
        }


        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                //取出私钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接受者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }

    }
}
